package com.cxs.netmanager.utils;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.io.*;

public abstract class ResponseCallBack<T> {
    static EventHandler mMainHandler = new EventHandler(EventRunner.getMainEventRunner());

    public ResponseCallBack() {
    }

    void onResponse(MyResponse myResponse) {
        final String buf = this.getRetString(myResponse.inputStream);
        mMainHandler.postTask(new Runnable() {
            @Override
            public void run() {
                ResponseCallBack.this.onSuccess(buf);
            }
        });
    }

    void onFailure(MyResponse response) {
        mMainHandler.postTask(new Runnable() {
            @Override
            public void run() {
                ResponseCallBack.this.onError(response);
            }
        });
    }

    public abstract void onSuccess(String var1);
    public abstract void onError(MyResponse response);

    private String getRetString(InputStream inputStream) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
